#include "Epoll.h"

Epoll::Epoll(int fd)
{
    this->m_fd=fd;
    init();
}

Epoll::~Epoll()
{
}

void Epoll::init()
{
    m_epfd = epoll_create(1);
    ev.data.fd = m_fd;
    ev.events = EPOLLIN;
    epoll_ctl(m_epfd, EPOLL_CTL_ADD, m_fd, &ev);
}

void Epoll::run()
{
    HEAD head={0};
    char body[1024]={0};
    ThreadPool pool;
    pool.start();
    for (;;)
    {
        int num = epoll_wait(m_epfd, evs, sizeof(evs), -1); // 阻塞等待
        if (num < 0)
        {
            perror("epoll wait error");
            continue;
        }
        for (int i = 0; i < num; i++)
        {
            if (evs[i].data.fd == m_fd)
            {
                int client_fd = accept(m_fd, NULL, NULL);
                cout << "有新客户端连接" << endl;
                struct epoll_event ev_c;
                ev_c.data.fd = client_fd;
                ev_c.events = EPOLLIN;
                epoll_ctl(m_epfd, EPOLL_CTL_ADD, client_fd, &ev_c);
            }
            else if (evs[i].events == EPOLLIN)
            {
                bzero(&head, sizeof(HEAD));
                bzero(body, sizeof(body));
                int clientfd = evs[i].data.fd;
                int size = read(clientfd, &head, sizeof(HEAD));
                if (size == 0)
                {
                    close(clientfd);
                    epoll_ctl(m_epfd, EPOLL_CTL_DEL, clientfd, NULL);
                }

                size = read(clientfd, body, head.data_len);
                if (size == 0)
                {
                    close(clientfd);
                    epoll_ctl(m_epfd, EPOLL_CTL_DEL, clientfd, NULL);
                }
                cout << "head.service_type =" << head.service_type << endl;
                BaseTask*task=nullptr;
                if (head.service_type == LOGIN)
                {
                    
                    task=TaskFactory::getTask(LOGIN,body,size,clientfd);
                }
                else if (head.service_type == CHAT)
                {
                    task=TaskFactory::getTask(CHAT,body,size,clientfd); 
                }
                else if (head.service_type == FRIEND)
                {
                    task=TaskFactory::getTask(FRIEND,body,size,clientfd);
                }
                if(task!=nullptr) 
                {
                    //pool.submitTask([task](){task->work();});
                }
            }
        }
    }
}
